package com.eastedu.superise.handler.question.callback;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eastedu.common.enums.QuestionTypeEnum;
import com.eastedu.repository.question.dto.QuestionItemDTO;
import com.eastedu.repository.question.mapper.QuestionBasicInfoMapper;
import com.eastedu.repository.question.mapper.QuestionItemMapper;
import com.eastedu.repository.question.po.QuestionBasicInfoPO;
import com.eastedu.repository.question.po.QuestionItemPO;
import com.eastedu.superise.handler.AbstractHistoricalDataHandler;
import com.eastedu.superise.handler.question.callback.handler.ChoiceQuestionAnswerParenthesesContentRollbackHandler;
import com.eastedu.superise.handler.question.callback.handler.StemContentRollbackConverter;
import com.eastedu.superise.handler.question.callback.handler.StemContentRollbackParser;
import com.eastedu.superise.handler.question.handler.answerparentheses.MatchType;
import com.eastedu.util.QuestionUtil;
import com.eastedu.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


/**
 * 单选、多选、不定项、判断题的题干新增结构化的作答括号 刷历史数据回滚修复公式
 *
 * @author superman
 */
@Slf4j
@Service
@DS("question")
public class ChoiceQuestionAnswerParenthesesRollbackHandler extends AbstractHistoricalDataHandler<QuestionBasicInfoPO> {
    private final QuestionBasicInfoMapper questionBasicInfoMapper;
    private final QuestionItemMapper questionItemMapper;
    private ChoiceQuestionAnswerParenthesesContentRollbackHandler handler;

    /**
     * Instantiates a new Choice question answer parentheses historical data handler.
     *
     * @param questionBasicInfoMapper the question basic info mapper
     * @param questionItemMapper      the question item mapper
     */
    public ChoiceQuestionAnswerParenthesesRollbackHandler(QuestionBasicInfoMapper questionBasicInfoMapper, QuestionItemMapper questionItemMapper) {
        this.questionBasicInfoMapper = questionBasicInfoMapper;
        this.questionItemMapper = questionItemMapper;
    }

    @Override
    protected String getSql() {
        handler = getContentHandler();
        /*
            故事ID：91067  0927】【功能】【建设中心】试题：客观题支持添加结构化括号
            将物理学科的历史客观题（单选、多选、不定项、判断）刷成结构化的内容（可优先高中，其次初中）
                1. 客观题题干中的空白括号（一般都在结尾，不排除特殊情况）
                2. 客观题题干中的下滑横线且横线上方无内容（可先处理了条件1后来看对应题型数量与已处理的数量差值来决定是否继续第二步）
           上次处理时间：2024-06-20 22:00:00， 处理的时间范围为：2024-09-09 00:00:00

           FIX: 刷历史数据回滚修复公式， 回滚时间：2024-09-09 00:00:00
         */
        return "SELECT " +
                "  DISTINCT b.* " +
                "FROM " +
                "   t_question_basic_info AS b  " +
                "WHERE b.audit_state = 2 " +
                "   AND b.study_period IN ('GZ','CZ') " +
                "   AND b.`subject` IN ('WL') " +
                "   AND b.`question_type` IN (1,2,3,5,7) " +
                "   AND b.create_time > 1725811200000 " +
                "ORDER BY b.id";
    }

    /**
     * Gets content handler.
     *
     * @return the content handler
     */
    protected ChoiceQuestionAnswerParenthesesContentRollbackHandler getContentHandler() {
        return new ChoiceQuestionAnswerParenthesesContentRollbackHandler(new StemContentRollbackParser(), new StemContentRollbackConverter());
    }

    @Override
    public void callback(QuestionBasicInfoPO questionBasicInfoPo) throws SQLException {
        List<QuestionItemPO> items = questionItemMapper.selectList(Wrappers.<QuestionItemPO>lambdaQuery().eq(QuestionItemPO::getQuestionId, questionBasicInfoPo.getId()));
        if (CollectionUtils.isEmpty(items)) {
            return;
        }

        // 将试题转换为嵌套结构
        List<QuestionItemDTO> questions = QuestionUtil.nestedSubItem(items, 0L);
        for (QuestionItemDTO item : questions) {

            if (handler.support(item, MatchType.IGNORE_ANSWER_ORDER)) {
                // 这里处理内容
                handler.handle(item);
                // 更新试题内容
                updateQuestionItem(item);
                // 更新综合题中的填空题
                if (questionBasicInfoPo.getQuestionType() == QuestionTypeEnum.COMPREHENSIVE) {
                    for (QuestionItemDTO question : item.getQuestions()) {
                        updateQuestionItem(question);
                    }
                }
                List<QuestionItemPO> pos = new ArrayList<>(16);
                QuestionUtil.flatSubItem(item, 0L, pos);


                QuestionBasicInfoPO po = new QuestionBasicInfoPO();
                po.setId(item.getQuestionId());
                po.setQuestion(JsonUtil.toJsonString(pos));

                this.questionBasicInfoMapper.updateById(po);
            }
        }
    }

    private void updateQuestionItem(QuestionItemDTO item) {
        this.questionItemMapper.update(Wrappers.<QuestionItemPO>lambdaUpdate()
                .set(QuestionItemPO::getContent, JsonUtil.toJsonString(item.getStem()))
                .eq(QuestionItemPO::getId, item.getId())
        );
    }

    @Override
    public void afterCompletion() {
        this.handler.print();
    }
}
